document.addEventListener('DOMContentLoaded', function() {
  const searchInput = document.getElementById('searchInput');
  const searchButton = document.getElementById('searchButton');

  searchButton.addEventListener('click', async function() {
    const searchText = searchInput.value.trim();
    if (!searchText) return;

    try {
      const [tab] = await chrome.tabs.query({active: true, currentWindow: true});
      
      // 注入并执行搜索高亮功能
      const [result] = await chrome.scripting.executeScript({
        target: { tabId: tab.id },
        func: highlightTextInPage,
        args: [searchText]
      });

      // 注入样式
      await chrome.scripting.insertCSS({
        target: { tabId: tab.id },
        css: `
          .extension-highlight {
            background-color: #ffeb3b !important;
            padding: 2px !important;
            border-radius: 2px !important;
            box-shadow: 0 0 0 1px rgba(0,0,0,0.1) !important;
          }
        `
      });

      if (result.result === 0) {
        alert('未找到匹配的内容');
      }
    } catch (err) {
      console.error('搜索操作失败:', err);
      alert('此页面不支持搜索高亮功能');
    }
  });

  searchInput.addEventListener('keypress', function(e) {
    if (e.key === 'Enter') {
      searchButton.click();
    }
  });
});

// 在页面中执行的搜索高亮函数
function highlightTextInPage(searchText) {
  // 清除现有的高亮
  const existingHighlights = document.querySelectorAll('.extension-highlight');
  existingHighlights.forEach(el => {
    const parent = el.parentNode;
    if (parent) {
      parent.replaceChild(document.createTextNode(el.textContent), el);
      parent.normalize(); // 合并相邻的文本节点
    }
  });

  if (!searchText) return 0;

  // 创建正则表达式
  const searchRegex = new RegExp(searchText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'gi');
  
  // 遍历文本节点
  const walker = document.createTreeWalker(
    document.body,
    NodeFilter.SHOW_TEXT,
    {
      acceptNode: function(node) {
        const parent = node.parentNode;
        return parent &&
               parent.nodeName !== 'SCRIPT' && 
               parent.nodeName !== 'STYLE' && 
               parent.nodeName !== 'MARK' &&
               parent.nodeName !== 'NOSCRIPT' &&
               !parent.classList.contains('extension-highlight') &&
               node.textContent.trim() !== ''
          ? NodeFilter.FILTER_ACCEPT 
          : NodeFilter.FILTER_REJECT;
      }
    }
  );

  let matchCount = 0;
  let node;
  const matches = [];
  
  // 收集所有匹配的节点
  while (node = walker.nextNode()) {
    if (searchRegex.test(node.textContent)) {
      matches.push(node);
    }
  }

  // 处理匹配的节点
  matches.forEach(node => {
    const fragment = document.createDocumentFragment();
    let lastIndex = 0;
    let match;

    // 重置正则表达式
    searchRegex.lastIndex = 0;
    
    while ((match = searchRegex.exec(node.textContent)) !== null) {
      // 添加匹配前的文本
      if (match.index > lastIndex) {
        fragment.appendChild(
          document.createTextNode(node.textContent.slice(lastIndex, match.index))
        );
      }
      
      // 创建高亮元素
      const mark = document.createElement('mark');
      mark.textContent = match[0];
      mark.className = 'extension-highlight';
      fragment.appendChild(mark);
      
      lastIndex = searchRegex.lastIndex;
      matchCount++;
    }
    
    // 添加剩余的文本
    if (lastIndex < node.textContent.length) {
      fragment.appendChild(
        document.createTextNode(node.textContent.slice(lastIndex))
      );
    }
    
    // 替换原始节点
    node.parentNode.replaceChild(fragment, node);
  });

  // 如果有匹配项，滚动到第一个
  if (matchCount > 0) {
    const firstMatch = document.querySelector('.extension-highlight');
    if (firstMatch) {
      firstMatch.scrollIntoView({
        behavior: 'smooth',
        block: 'center'
      });
    }
  }

  return matchCount;
} 